import React, { useState } from 'react';
import {
  Box,
  Card,
  CardContent,
  TextField,
  Button,
  Typography,
  Alert,
  InputAdornment,
  IconButton,
  CircularProgress,
} from '@mui/material';
import {
  Visibility,
  VisibilityOff,
  Business,
  Person,
  Lock,
} from '@mui/icons-material';
import { useForm } from 'react-hook-form';

import { useAuth } from '@/stores';
import { LoginCredentials } from '@/types';
import { commonStyles } from '@/styles/utils';

interface LoginFormData {
  username: string;
  password: string;
  tenantCode?: string;
}

export const LoginPage: React.FC = () => {
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState<string | null>(null);
  
  const { login, isLoading } = useAuth();
  
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<LoginFormData>({
    defaultValues: {
      username: 'admin',
      password: 'admin123',
      tenantCode: 'aliyun',
    },
  });

  const onSubmit = async (data: LoginFormData) => {
    try {
      setError(null);
      const credentials: LoginCredentials = {
        username: data.username,
        password: data.password,
        tenantCode: data.tenantCode,
      };
      await login(credentials);
    } catch (err) {
      setError(err instanceof Error ? err.message : '登录失败');
    }
  };

  const togglePasswordVisibility = () => {
    setShowPassword(!showPassword);
  };

  return (
    <Box
      sx={{
        ...commonStyles.flexCenter,
        minHeight: '100vh',
        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
        p: 2,
      }}
    >
      <Card
        sx={{
          maxWidth: 400,
          width: '100%',
          borderRadius: 3,
          boxShadow: '0 8px 32px rgba(0, 0, 0, 0.1)',
        }}
      >
        <CardContent sx={{ p: 4 }}>
          {/* 标题 */}
          <Box sx={{ textAlign: 'center', mb: 4 }}>
            <Business sx={{ fontSize: 48, color: 'primary.main', mb: 1 }} />
            <Typography variant="h4" sx={{ fontWeight: 600, mb: 1 }}>
              系统登录
            </Typography>
            <Typography variant="body2" color="text.secondary">
              多租户多组织管理系统
            </Typography>
          </Box>

          {/* 错误提示 */}
          {error && (
            <Alert severity="error" sx={{ mb: 3 }}>
              {error}
            </Alert>
          )}

          {/* 登录表单 */}
          <Box component="form" onSubmit={handleSubmit(onSubmit)}>
            {/* 租户代码 */}
            <TextField
              fullWidth
              label="租户代码"
              variant="outlined"
              margin="normal"
              disabled={isLoading}
              error={!!errors.tenantCode}
              helperText={errors.tenantCode?.message}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <Business />
                  </InputAdornment>
                ),
              }}
              {...register('tenantCode', {
                required: '请输入租户代码',
              })}
            />

            {/* 用户名 */}
            <TextField
              fullWidth
              label="用户名"
              variant="outlined"
              margin="normal"
              disabled={isLoading}
              error={!!errors.username}
              helperText={errors.username?.message}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <Person />
                  </InputAdornment>
                ),
              }}
              {...register('username', {
                required: '请输入用户名',
              })}
            />

            {/* 密码 */}
            <TextField
              fullWidth
              label="密码"
              type={showPassword ? 'text' : 'password'}
              variant="outlined"
              margin="normal"
              disabled={isLoading}
              error={!!errors.password}
              helperText={errors.password?.message}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <Lock />
                  </InputAdornment>
                ),
                endAdornment: (
                  <InputAdornment position="end">
                    <IconButton
                      onClick={togglePasswordVisibility}
                      edge="end"
                      disabled={isLoading}
                    >
                      {showPassword ? <VisibilityOff /> : <Visibility />}
                    </IconButton>
                  </InputAdornment>
                ),
              }}
              {...register('password', {
                required: '请输入密码',
              })}
            />

            {/* 登录按钮 */}
            <Button
              type="submit"
              fullWidth
              variant="contained"
              size="large"
              disabled={isLoading}
              sx={{
                mt: 3,
                mb: 2,
                height: 48,
                borderRadius: 2,
                textTransform: 'none',
                fontSize: '1rem',
              }}
            >
              {isLoading ? (
                <CircularProgress size={24} color="inherit" />
              ) : (
                '登录'
              )}
            </Button>
          </Box>

          {/* 演示账号提示 */}
          <Box sx={{ mt: 3, p: 2, backgroundColor: 'action.hover', borderRadius: 1 }}>
            <Typography variant="caption" color="text.secondary" sx={{ display: 'block' }}>
              演示账号：
            </Typography>
            <Typography variant="body2" sx={{ mt: 0.5 }}>
              租户代码：aliyun
            </Typography>
            <Typography variant="body2">
              用户名：admin
            </Typography>
            <Typography variant="body2">
              密码：admin123
            </Typography>
          </Box>
        </CardContent>
      </Card>
    </Box>
  );
};

export default LoginPage;